package View.acao;

import Data.UsuarioDAO;
import Model.UsuarioBean;
import java.sql.SQLException;
import javax.swing.JOptionPane;

public class CadastrarUsuario extends javax.swing.JInternalFrame {

    private UsuarioBean usuario_alterar = null;

    public CadastrarUsuario() {
        initComponents();
    }

    public CadastrarUsuario(UsuarioBean usuario) {
        initComponents();
        usuario_alterar = usuario;

        if (usuario_alterar != null) {
            jtf_login.setText(usuario.getLogin());
            jtf_nome.setText(usuario.getNome());
            jLabel3.setText("Senha Antiga");
            jLabel4.setText("Nova senha");
            admin.setSelected(usuario.isAdmin());
        } else {
            JOptionPane.showMessageDialog(rootPane, "Erro ao recuperar usuario!", "Erro!", JOptionPane.ERROR_MESSAGE);
            dispose();
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jtf_nome = new javax.swing.JTextField();
        jtf_login = new javax.swing.JTextField();
        jpf_senha = new javax.swing.JPasswordField();
        jpf_confsenha = new javax.swing.JPasswordField();
        admin = new javax.swing.JCheckBox();

        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Cadastrar Usuario");

        jLabel1.setText("Nome:");

        jLabel2.setText("Login:");

        jLabel3.setText("Senha:");

        jLabel4.setText("Confirmar Senha:");

        jButton1.setText("Salvar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Cancelar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        admin.setText("Administrador");

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                        .add(0, 195, Short.MAX_VALUE)
                        .add(jButton1)
                        .add(45, 45, 45)
                        .add(jButton2))
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(admin)
                            .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                .add(jLabel1)
                                .add(jLabel2)
                                .add(jLabel3)
                                .add(jLabel4)))
                        .add(26, 26, 26)
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jtf_nome)
                            .add(jtf_login)
                            .add(jpf_senha)
                            .add(jpf_confsenha))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel1)
                    .add(jtf_nome, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel2)
                    .add(jtf_login, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel3)
                    .add(jpf_senha, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel4)
                    .add(jpf_confsenha, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(30, 30, 30)
                .add(admin)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jButton1)
                    .add(jButton2))
                .addContainerGap())
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(14, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if (validar()) {
            UsuarioDAO data = new UsuarioDAO();
            UsuarioBean usuario = new UsuarioBean();

            usuario.setNome(jtf_nome.getText());
            usuario.setLogin(jtf_login.getText());
            usuario.setSenha(jpf_senha.getText());
            usuario.setAdmin(admin.isSelected());

            try {
                //Alteração
                if (usuario_alterar != null) {
                    usuario.setSenha(jpf_confsenha.getText());
                    usuario.setCodigo(usuario_alterar.getCodigo());
                    boolean resultado = false;

                    if (!jpf_confsenha.getText().isEmpty()) {
                        resultado = data.atualizarUsuario(usuario, true);
                    } else {
                        resultado = data.atualizarUsuario(usuario, false);
                    }
                    if (resultado) {
                        JOptionPane.showMessageDialog(rootPane, "Alterado com sucesso!");
                        dispose();
                    } else {
                        throw new SQLException("Erro ao atualizar usuario!");
                    }
                } else {
                    //Cadastro
                    if (data.cadastrarUsuario(usuario)) {
                        JOptionPane.showMessageDialog(rootPane, "Usuario cadastrado com sucesso!");
                        dispose();
                    } else {
                        throw new SQLException("Erro ao cadastrar usuario!");
                    }
                }

            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(rootPane, ex.getMessage(), "Erro!", JOptionPane.ERROR_MESSAGE);
            }

        }
    }//GEN-LAST:event_jButton1ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JCheckBox admin;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPasswordField jpf_confsenha;
    private javax.swing.JPasswordField jpf_senha;
    private javax.swing.JTextField jtf_login;
    private javax.swing.JTextField jtf_nome;
    // End of variables declaration//GEN-END:variables

    private boolean validar() {
        try {
            if (jtf_nome.getText().isEmpty()) {
                throw new Exception("Digite um nome!");
            }

            if (jtf_login.getText().isEmpty()) {
                throw new Exception("Digite um login!");
            }
            //É uma edição
            if (usuario_alterar != null) {
                //Verifica se vai alterar a senha
                if (!jpf_senha.getText().isEmpty()) {
                    //Se estiver algo digitado na senha antiga checo se tem algo na nova senha
                    if (jpf_confsenha.getText().isEmpty()) {
                        throw new Exception("Digite uma nova senha!");
                    }
                    //comparo com a senha antiga para ver se bate
                    if (!jpf_senha.getText().equals(usuario_alterar.getSenha())) {
                        throw new Exception("A senha antiga não confere!");
                    }
                }
            } else {
                if (!jpf_senha.getText().equalsIgnoreCase(jpf_confsenha.getText())) {
                    throw new Exception("As senhas digitadas não conferem!");
                }
            }
            return true;
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(rootPane, ex.getMessage(), "Aviso!", JOptionPane.WARNING_MESSAGE);
            return false;
        }
    }
}
